package com.fs.zx.mybatis.starter;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Slf4j
@Configuration
@EnableConfigurationProperties(ZxDataSourceProperties.class)
@ConditionalOnProperty(prefix = "zx.datasource", value = "enable", matchIfMissing = true)
public class MybatisDataSourceAutoConfiguration {

    @Autowired
    ZxDataSourceProperties properties;



    @Bean
    @ConditionalOnMissingBean(DataSource.class)
    public DataSource dataSource() {
        log.info("MybatisDataSourceAutoConfiguration dataSource");
        HikariDataSource dataSource = new HikariDataSource();
        try {
            log.info("datasource init....");
            dataSource.setPoolName(properties.getPoolName());
            dataSource.setDriverClassName(properties.getDriverName());
            dataSource.setJdbcUrl(properties.getUrl());
            dataSource.setUsername(properties.getUserName());
            dataSource.setPassword(properties.getPassword());
            dataSource.setMaximumPoolSize(properties.getMaxActive());
            dataSource.setMinimumIdle(properties.getMinIdle());
            dataSource.setIdleTimeout(properties.getIdleTimeOut());
            dataSource.setConnectionTimeout(properties.getConnectionTimeOut());
            dataSource.setConnectionTestQuery(properties.getValidationQuery());
            dataSource.setAutoCommit(true);
        } catch (Exception e) {
            log.error("createDataSource Error", e);
        }
        return dataSource;
    }

    @ConditionalOnMissingBean(SqlSessionFactory.class)
    @Bean
    public SqlSessionFactory sqlSessionFactory(ConfigurableApplicationContext context) throws Exception {
        log.info("MybatisSpringConfig sqlSessionFactory");
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setDataSource(this.dataSource());
        ssfb.setTypeAliasesPackage(properties.getMybatisBasePackage());
        ssfb.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(properties.getMybatisBasePath()));
        return ssfb.getObject();
    }

}
